package com.qf.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断 请求 中是否包含token数据
        //获取 request中的token数据
        //exchange 交换机
        ServerHttpRequest request = exchange.getRequest();
        //从请求头中获取数据
//        request.getHeaders().get()

        //获取获取 request中的所有请求参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //从请求参数中获取 token数据
        String token = queryParams.getFirst("token");


        //判断是否有token，  如果有则放行，登录成功
        if(!StringUtils.isEmpty(token)) {
            System.out.println("认证成功，请继续操作");
//            exchange.getResponse().setStatusCode(HttpStatus.OK);
//            return exchange.getResponse().setComplete();
            //放行
            return chain.filter(exchange);
        }
        //如果没有token， 则登录失败，返回 401 状态码
        else {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }

    /**
     * 返回值可以表示 过滤器的执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
